package org.openea.eap.module.obpm.service.singlelogin.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.openea.eap.module.obpm.service.singlelogin.config.ApiConfiguration;
import org.openea.eap.module.obpm.service.singlelogin.model.LoginRequest;
import org.openea.eap.module.obpm.service.singlelogin.model.LoginResponse;
import org.openea.eap.module.obpm.service.singlelogin.util.HttpHeadersUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    private final ApiConfiguration apiConfig;

    @Autowired
    public LoginServiceImpl(ApiConfiguration apiConfig) {
        this.apiConfig = apiConfig;
    }

    @Override
    public LoginResponse login(String token, String ip) {

        log.info("配置文件===>{}", apiConfig);

        String url = apiConfig.getBaseUrl() + "?X-Sec-App-Auth-Key=" + apiConfig.getAppAuthKey();
        Map<String, String> headers = HttpHeadersUtil.createHeaders(apiConfig);
        LoginRequest request = createLoginRequest(token, ip);

        try {
            HttpResponse response = HttpRequest.post(url)
                    .headerMap(headers, true)
                    .body(JSONUtil.toJsonStr(request))
                    .execute();

            if (response.isOk()) {
                LoginResponse loginResponse = JSONUtil.toBean(response.body(), LoginResponse.class);
                if (loginResponse != null && !loginResponse.isError() && "200".equals(loginResponse.getCode())) {
                    return loginResponse;
                }
            }
        } catch (Exception e) {
            log.error("解析token报错", e);
        }

        return null;
    }

    private LoginRequest createLoginRequest(String token, String ip) {
        return LoginRequest.builder()
                .token(token)
                .hasCompanyInfo(true)
                .hasAuthInfo(true)
                .logInfo(LoginRequest.LogInfo.builder()
                        .ip(ip)
                        .host(ip)
                        .build())
                .build();
    }
}
